﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using UL360DataNET40;

namespace UL360Admin.Survey
{
    public partial class SurveyFormEditor : System.Web.UI.Page
    {
        string MethodName = System.Reflection.MethodBase.GetCurrentMethod().Name;
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                //Set default surveyType
                SurveyType surveyType = 0;

                //Get requested surveyType from querystring
                if (Request.QueryString["FormType"] != null)
                {
                    int formType = 0;
                    int.TryParse(Request.QueryString["FormType"], out formType);
                    surveyType = (SurveyType)formType;

                    if (surveyType == SurveyType.ExtendedCourse)
                    {
                        EditSurveyTitle.Text = "Redigera enkätformulär för kursutvärdering del 2";
                    }
                }

                //Set hidden field
                FormType.Value = surveyType.ToString();

                //List with questions to add to requested form
                IQueryable<SurveyQuestion> questions;
                //List with languages
                IQueryable<Sprak> languages;
                //Get questions from db
                using (var db = new UL360Entities())
                {
                    //Get form with latest version where surveyType match the requested type
                    var forms = db.SurveyForms.Include("SurveyQuestions.SurveyQuestionTexts.Sprak").Where(f => f.SurveyType == (int)surveyType).OrderByDescending(f => f.DateCreated).FirstOrDefault();

                    //Get languages
                    languages = db.Spraks.DefaultIfEmpty(null).ToList().AsQueryable();

                    //Get questions of form if form was found and show the date when the form was last saved
                    if (forms != null && forms.SurveyQuestions.Count > 0)
                    {
                        questions = forms.SurveyQuestions.AsQueryable();
                        DateCreated.Text = "Skapad den: " + forms.DateCreated.Date.ToString("yyyy-MM-dd");
                        SurveyVersion.Text = "Version: " + forms.SurveyFormId.ToString();
                    }
                    else
                    {
                        questions = new List<SurveyQuestion>().AsQueryable();
                    }
                }

                if (languages != null)
                {
                    foreach (Sprak language in languages)
                    {
                        LanguagesList.Value += language.sprakid + "#" + language.namn + ";";
                    }
                }

                //Add order count to scale questions
                if (questions.Where(q => q.QuestionType == (int)QuestionType.Scale).ToList().Count > 0)
                {
                    ScaleOrderCount.Value = questions.Where(q => q.QuestionType == (int)QuestionType.Scale).OrderByDescending(q => q.Order).First().Order.ToString();
                }
                else
                {
                    ScaleOrderCount.Value = "0";
                }

                //Add order count to text questions
                if (questions.Where(q => q.QuestionType == (int)QuestionType.Text).ToList().Count > 0)
                {
                    TextOrderCount.Value = questions.Where(q => q.QuestionType == (int)QuestionType.Text).OrderByDescending(q => q.Order).First().Order.ToString();
                }
                else
                {
                    TextOrderCount.Value = "0";
                }

                //Bind scalequestions as datasource to control in form
                ScaleQuestions.DataSource = questions.Where(q => q.QuestionType == (int)QuestionType.Scale).ToList();
                ScaleQuestions.DataBind();

                //Loop through each question item in control to add texts to inner listview
                foreach (RepeaterItem questionItem in ScaleQuestions.Items)
                {
                    //Get question ID
                    int questionId;
                    int.TryParse(((HiddenField)questionItem.FindControl("ScaleQuestionID")).Value, out questionId);

                    //Get question Order
                    int questionNumber;
                    int.TryParse(((Label)questionItem.FindControl("ScaleQuestionNumber")).Text, out questionNumber);

                    //Bind question texts to inner listview of questionitem by questionId
                    ((Repeater)(questionItem.FindControl("Languages"))).DataSource = languages.ToList();
                    ((Repeater)(questionItem.FindControl("Languages"))).DataBind();

                    foreach (RepeaterItem languageItem in ((Repeater)(questionItem.FindControl("Languages"))).Items)
                    {
                        //Get language ID
                        int languageId;
                        int.TryParse(((HiddenField)languageItem.FindControl("LanguageId")).Value, out languageId);

                        ((TextBox)(languageItem.FindControl("ScaleQuestionText"))).ID += questionNumber.ToString() + "#" + languageId.ToString();
                        ((TextBox)(languageItem.FindControl("ScaleQuestionText" + questionNumber.ToString() + "#" + languageId.ToString()))).Text = questions.Where(q => q.SurveyQuestionId == questionId).First()
                            .SurveyQuestionTexts.Where(t => t.fk_SprakId == languageId).DefaultIfEmpty(new SurveyQuestionText()).First().Question;
                    }
                }

                //Bind textquestions as datasource to control in form
                TextQuestions.DataSource = questions.Where(q => q.QuestionType == (int)QuestionType.Text).ToList();
                TextQuestions.DataBind();

                //Loop through each question item in control to add texts to inner listview
                foreach (RepeaterItem questionItem in TextQuestions.Items)
                {
                    //Get question ID
                    int questionId;
                    int.TryParse(((HiddenField)questionItem.FindControl("TextQuestionID")).Value, out questionId);

                    //Get question Order
                    int questionNumber;
                    int.TryParse(((Label)questionItem.FindControl("TextQuestionNumber")).Text, out questionNumber);

                    //Bind question texts to inner listview of questionitem by questionId
                    ((Repeater)(questionItem.FindControl("Languages"))).DataSource = languages.ToList();
                    ((Repeater)(questionItem.FindControl("Languages"))).DataBind();

                    foreach (RepeaterItem languageItem in ((Repeater)(questionItem.FindControl("Languages"))).Items)
                    {
                        //Get language ID
                        int languageId;
                        int.TryParse(((HiddenField)languageItem.FindControl("LanguageId")).Value, out languageId);

                        ((TextBox)(languageItem.FindControl("TextQuestionText"))).ID += questionNumber.ToString() + "#" + languageId.ToString();
                        ((TextBox)(languageItem.FindControl("TextQuestionText" + questionNumber.ToString() + "#" + languageId.ToString()))).Text = questions.Where(q => q.SurveyQuestionId == questionId).First()
                            .SurveyQuestionTexts.Where(t => t.fk_SprakId == languageId).DefaultIfEmpty(new SurveyQuestionText()).First().Question;
                    }
                }

                //Show information that form has no questions
                if (questions.ToList().Count <= 0)
                {
                    InformationLabel.Text = GetLocalResourceObject("NoQuestionsInForm").ToString();
                    
                    //Hide buttons if no questions are available
                    ButtonPanel.Attributes.CssStyle[HtmlTextWriterStyle.Display] = "none";
                    Save1.Attributes.CssStyle[HtmlTextWriterStyle.Display] = "none";
                }
                else if (questions.Where(q => q.QuestionType == (int)QuestionType.Scale).ToList().Count == 0)
                {
                    NoScaleQuestionsInForm.Text = GetLocalResourceObject("NoScaleQuestionsInForm").ToString();
                }
                else if (questions.Where(q => q.QuestionType == (int)QuestionType.Text).ToList().Count == 0) 
                {
                    NoTextQuestionsInForm.Text = GetLocalResourceObject("NoTextQuestionsInForm").ToString();
                }


            }
            catch (Exception exc)
            {
                string errorTicket = UL360SurveyCommon.LoggerCommon.LogNewEntry(
                    new UL360SurveyCommon.LoggerCommon.LogNewEntryDelegate(UL360Admin.Survey.Utils.Logger.LogNewEntry), 
                    MethodName, exc.ToString(), (int)UL360SurveyCommon.SurveyLoggingLevel.Error);

                WarningLabel.Text = string.Format(GetLocalResourceObject("ExceptionOccured").ToString() + " {0}", errorTicket);
            }
        }
    }
}